package com.jun.rabbitmq.consumer.listener;

import cn.hutool.json.JSONUtil;
import com.jun.common.core.entity.mq.RabbitMQRequestEntity;
import com.jun.common.core.exception.ServiceException;
import com.jun.common.rabbitmq.constant.QueueConstant;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author yuejun.li
 * @date 2024/4/18 13:41:00
 */
@Component
@Slf4j
public class DirectListener {

    /*@RabbitListener(queues = QueueConstant.TEST_DIRECT_QUEUE)
    public void process(RabbitMQRequestEntity<String> testMessage) {
        System.out.println("第一个消费者收到消息: " + testMessage.toString());
        int i = 10/0;
    }*/


    //auto、none模式
    /*@RabbitListener(queues = QueueConstant.TEST_DIRECT_QUEUE,ackMode = "AUTO")
    public void errorProcess1(String testMessage) {
        RabbitMQRequestEntity rabbitMQRequestEntity = JSONUtil.toBean(testMessage, RabbitMQRequestEntity.class);
        System.out.println("第三个消费者收到消息: " + rabbitMQRequestEntity);
        //模拟异常
        throw new RuntimeException("乱跑异常");
    }*/

    //manual模式
    @RabbitListener(queues = QueueConstant.TEST_DIRECT_QUEUE)
    public void errorProcess2(RabbitMQRequestEntity testMessage, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws Exception {
        int retry = 3;
        while (retry > 0) {
            //模拟异常
            try {
                System.out.println("第四个消费者正在消费" + testMessage);
                int i = 1/0;
                //deliveryTag 批量处理的标号 第二个参数为false是表示仅仅确认当前消息 true表示确认之前所有的消息
                channel.basicAck(deliveryTag,false);
            }catch (Exception e){
                throw e;
                //retry--;
            }finally{
                if(retry <= 0){
                    //nack可以操作多条，requeue 是否送回队列（若其他消费者要消费，可以选择送回，否则就不送回）
                    channel.basicNack(deliveryTag,false,false);
                    //reject只能操作一条，requeue 是否送回队列
                    //channel.basicReject(deliveryTag,false);
                }
            }
        }
    }

    // 抢到礼品人数
    public static List<RabbitMQRequestEntity> list = new ArrayList<>();
    // 抢购人数
    public static int number = 0;
    // 抢购人数原子类
    public static volatile AtomicInteger count = new AtomicInteger(0);
    // 没抢到礼品人数
    public static volatile AtomicInteger noRobCount = new AtomicInteger(0);
    // 抢到礼品人数
    public static volatile AtomicInteger yesRobCount = new AtomicInteger(0);

    //@RabbitListener(queues = QueueConstant.TEST_DIRECT_QUEUE_3,ackMode = "MANUAL")
    public void errorProcess3(RabbitMQRequestEntity testMessage,Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException {
        String name = testMessage.getData().toString();
        number += 1;
        count.incrementAndGet();
        if (list.size() == 10) {
            noRobCount.incrementAndGet();
            log.error("活动结束，无礼品！ {}同学不要灰心，下次肯定是你！", name);
            channel.basicNack(deliveryTag, false, false);
            //channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            return;
        }
        yesRobCount.incrementAndGet();
        channel.basicAck(deliveryTag, false);
        list.add(testMessage);
        log.info("恭喜 {} 同学抢到礼品>>>>>>>>>>>>>>>>>>>> ", name);
    }
}
